<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\admin\model\AdminUser;
use app\admin\model\AuthRule as AuthRules;
use app\admin\validate\CheckAdminUser;
use app\common\controller\AdminBaseController;
use app\common\model\tang\CostRule;
use app\common\model\tang\CostType;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\StaffRule;
use app\common\model\tang\SubjectList;
use think\facade\Config;
use think\facade\Db;
use app\common\model\tang\BalanceLog;

class Certificate extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\common\model\tang\Cost();
    }


    public function index()
    {
        if (IS_AJAX){
            return $this->model->getAdminPageData($this->param, 'id desc',['type'=>3,'pid'=>0]);
        }
        $merchant_list =\app\common\model\tang\Merchant::field('id,merchant_sn,name,company,username,code')->select();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }

    public function detail1()
    {
        return $this->fetch();
    }
    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:添加编辑
     */
    public function add()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            if (empty($data['datas'])){
                return parent::JsonReturn('缴费项不存在', 0);
            }
            if (isset($data['date_type']) && $data['date_type'] == 'on'){
                $data['date_type'] = 1;
            }else{
                $data['date_type'] = 0;
                if(!empty($data['date'])){
                    $time = explode(' - ',$data['date']);
                    $data['start_time']  = strtotime($time[0]) ;
                    $data['end_time']    = strtotime($time[1]) ;
                }
            }
            Db::startTrans();
            try {
                $model =  new \app\common\model\tang\Cost();
                if($data['merchant_type']==2){  //临时商户缴费
                    if (empty($data['merch_username'])){
                        return parent::JsonReturn('商户姓名不能为空', 0);
                    }
                    if (empty($data['merch_mobile'])){
                        return parent::JsonReturn('商户手机号码不能为空', 0);
                    }
                    // 创建新商户
                    $merchant_id = (new MerchantModel())->AddMerchant($data['merch_username'],$data['merch_mobile']);
                    if(!$merchant_id){
                        return self::JsonReturn("手机号码已被注册", 0);
                    }else{
                        $data['merchant_id'] = $merchant_id ;
                        unset($data['merch_username']);
                        unset($data['merch_mobile']);
                    }
                }
                unset($data['__token__']);
//                unset($data['date']);
                unset($data['file']);
                unset($data['merchant_type']);
                $data['number'] = intval($data['number']);  // 购买数量
                $unit_price = 0 ;
                $amount = 0 ;
                foreach ($data['datas'] as $v){
                    $unit_price += $v['unitprice'] ;
                    $amount += $v['z_money'] ;
                }
                if((int)$amount!=(int)$data['real_amount']){
                    return parent::JsonReturn('订单价格错误', 0);
                }
                $data['amount'] = intval($amount * 100);
                $data['unit_price'] = $unit_price ; // 单价
                $data['real_amount'] =intval($data['real_amount'] * 100);
                $data['add_user'] = static::$admin_info['nickname'];
                $data['order_sn'] = OrderSn();
                $model->save($data);
                // 添加了缴费人员
                if(!empty($data['personArray'])){
                    // 查询已添加
                    $sum = count($data['personArray']);
                    if($sum>$data['number']){
                        return parent::JsonReturn('添加的用户数量大于办理数', 1);
                    }
                    $personArray = [];
                    foreach ($data['personArray'] as $k => $row){
                        if($data['date_type']==0){
                            $personArray[$k]['start_time'] = $data['start_time'];
                            $personArray[$k]['end_time'] = $data['end_time'];
                        }
                        $personArray[$k]['pid'] =  $model->id;
                        $personArray[$k]['merchant_id'] = $data['merchant_id'];
                        $personArray[$k]['pay_status'] = 1;
                        $personArray[$k]['unit_price'] = 0;
                        $personArray[$k]['date_type'] = $data['date_type'];
                        $personArray[$k]['department_id'] = $data['department_id'];
                        $personArray[$k]['cost_type_id'] = $data['cost_type_id'];
                        $personArray[$k]['order_sn'] = OrderSn();
                        $personArray[$k]['pay_time'] = date('Y-m-d H:i:s',time());
                        if(!empty($row['mobile'])){
                            $personArray[$k]['mobile'] = $row['mobile'];
                        }else{
                            return parent::JsonReturn('施工人员手机号码不能为空', 1);
                        }
                        if(!empty($row['username'])){
                            $personArray[$k]['username'] = $row['username'];
                        }else{
                            return parent::JsonReturn('施工人员姓名不能为空', 1);
                        }
                        if(!empty($row['card_number'])){
                            $personArray[$k]['card_number'] = $row['card_number'];
                        }
                        if(!empty($row['other_certificate'])){
                            $personArray[$k]['other_certificate'] = $row['other_certificate'];
                        }
                        if(!empty($row['id_card_positive'])){
                            $personArray[$k]['id_card_positive'] = $row['id_card_positive'];
                        }
                        if(!empty($row['id_card_negative'])){
                            $personArray[$k]['id_card_negative'] = $row['id_card_negative'];
                        }
                    }
                    $this->model->insertAll($personArray);
                }
                $arr = [];
                foreach ($data['datas'] as $key=>$value){
                    $arr[$key]['name'] = $value['cost_name'];
                    $arr[$key]['type'] = $value['type'];
                    $arr[$key]['unitprice'] = $value['unitprice'];
                    $arr[$key]['money'] = $value['money'];
                    $arr[$key]['z_money'] = $value['z_money'];
                    $arr[$key]['cost_sn'] = $value['cost_sn'];
                    $arr[$key]['tax_sn'] = $value['tax_sn'];
                    $arr[$key]['tax_money'] = $value['tax_money'];
                    $arr[$key]['cost_type_id'] = $value['id'];
                    $arr[$key]['tax_rate'] = $value['tax_rate'];
                    $arr[$key]['pid'] = $model->id;
                    $arr[$key]['create_time'] = time();
                }
                (new CostRule())->insertAll($arr);
                Db::commit();
                return self::JsonReturn("添加成功");
            }catch (\Exception $exception){
                Db::rollback();
                return self::JsonReturn($exception->getMessage(),0);
            }
        }
        $merchant_list = (new MerchantModel())->where('status' ,'<>',-1)->field('id,merchant_sn,name,company')->select();
        $cost_type_list = (new CostType())
            ->where('type','=',3)
            ->where('pid','=',0)
            ->field('id,cost_name')->select();
        $service_charge = (\app\common\model\tang\System::where(['id'=>3])->value('amount'))/100;

        $pay_type = (new SubjectList())->where('type','=',1)->field('id,name')->select();
        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id);
        //所属部门
        $department_list = SubjectList::where('type','=',2)->field('id,name')->select();
        //获取菜单列表
        $this->assign(compact("info", "id","merchant_list","cost_type_list",'department_list',"pay_type","service_charge"));
        return $this->fetch();
    }

    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/7/12 0030
     * @describe:检测是否有需要退还的押金
     */
    public function IsRebate(){
        if (IS_AJAX) {
            $id = $this->request->param("id/d");
            $info = $this->model->with(['costRule'])->find($id);
            if($info->pay_status!=1){
                return parent::JsonReturn('订单不能退款', 1);
            }
            $arr = [] ;
            if(!empty($info->costRule)){
                foreach ($info->costRule as $v){
                    if($v['type']==1){
                        $arr[] = $v ;
                    }
                }
                if(empty($arr)){
                    return parent::JsonReturn('没有可退款的项目', 1);
                }else{
                    return self::ajaxResult($arr,0,0,'success');
                }
            }else{
                return parent::JsonReturn('没有可退款的项目', 1);
            }

        }
    }

    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/7/12 0030
     * @describe:退还押金
     */
    public function rebate(){
        if (IS_AJAX) {
            $data = $this->request->post();

            if(empty($data['id'])){
                return parent::JsonReturn('ID不能为空', 1);
            }
            $info = $this->model->with(['merchants'])->find($data['id']);

            if($info){
                $remark = $data['remark'] ;
                $type = $data['type'] ; // 1 冲入余额
                if($info->pay_status!=1){
                    return parent::JsonReturn('订单未支付或已退款', 1);
                }
                Db::startTrans();
                try {
                    if($type==1){
                        $total = 0 ;
                        foreach ($info->costRule as& $v){
                            if($v['type']==1){
                                $total+= $v['z_money'] ;
                            }
                        }
                        $model = new BalanceLog() ;
                        $model->merchant_id = $info->merchant_id;
                        $model->order_sn = $info->order_sn;
                        $model->is_top_up = 3 ;
                        $model->edit = 1;
                        $model->status = 1;
                        $model->amount =  $total*100;
                        $model->remark = $remark;
                        $model->create_time = time();
                        $model->save();
                        $user = (new MerchantModel())->find($info->merchant_id);
                        $balance = $user->balance+$total*100;
                        (new MerchantModel())->update(['balance'=>$balance],['id'=>$info->merchant_id]);

                    }
                    $this->model->update(['pay_status'=>-1,'remark'=>$remark],['id'=>$data['id']]);
                    Db::commit();
                    return self::JsonReturn("退款成功");
                }catch (\Exception $exception){
                    Db::rollback();
                    return self::JsonReturn($exception->getMessage(),0);
                }
            }else{
                return parent::JsonReturn('退款订单不存在', 1);
            }
        }
        $id = $this->request->param("id/d");
        $info = $this->model->with(['costRule'])->find($id);
        $arr = [] ;
        $total = 0 ;
        foreach ($info->costRule as& $v){
            if($v['type']==1){
                $v['type'] = '押金' ;
                $arr[] = $v ;
                $total+= $v['z_money'] ;
            }
        }
        $this->assign(compact("info", "id","arr","total"));
        return $this->fetch();
    }

    public function adminAdd()
    {

        if (IS_AJAX) {
            $data = $this->request->post();
            if (empty($data['datas'])){
                return parent::JsonReturn('缴费项不存在', 0);
            }
            if (isset($data['date_type']) && $data['date_type'] == 'on'){
                $data['date_type'] = 1;
            }
            Db::startTrans();
            try {
                $model =  new \app\common\model\tang\Cost();
                if($data['merchant_type']==2){  //临时商户缴费
                    if (empty($data['merch_username'])){
                        return parent::JsonReturn('商户姓名不能为空', 0);
                    }
                    if (empty($data['merch_mobile'])){
                        return parent::JsonReturn('商户手机号码不能为空', 0);
                    }
                    // 创建新商户
                    $merchant_id = (new MerchantModel())->AddMerchant($data['merch_username'],$data['merch_mobile']);
                    if(!$merchant_id){
                        return self::JsonReturn("手机号码已被注册", 0);
                    }else{
                        $data['merchant_id'] = $merchant_id ;
                        unset($data['merch_username']);
                        unset($data['merch_mobile']);
                    }
                }
                unset($data['__token__']);
                unset($data['date']);
                unset($data['file']);
                unset($data['merchant_type']);
                $data['service_charge'] = intval($data['service_charge'] * 100);
                $data['real_amount'] =   intval($data['real_amount'] * 100);
                $data['amount'] = $data['real_amount'];
                $data['add_user'] = static::$admin_info['nickname'];
                $data['order_sn'] = OrderSn();;
                $model->save($data);
                $arr = [];
                foreach ($data['datas'] as $key=>$value){
                    $arr[$key]['name'] = $value['name'];
                    $arr[$key]['type'] = $value['type'];
                    $arr[$key]['amount'] = $value['amount'];
                    $arr[$key]['cost_sn'] = $value['cost_sn'];
                    $arr[$key]['cost_type_id'] = $value['id'];
                    $arr[$key]['tax_rate'] = $value['tax_rate'];
                    $arr[$key]['rate'] = $value['rate'];
                    $arr[$key]['pid'] = $model->id;
                }
                (new CostRule())->insertAll($arr);
                Db::commit();
                return self::JsonReturn("添加成功");
            }catch (\Exception $exception){
                Db::rollback();
                return self::JsonReturn($exception->getMessage(),0);
            }
        }

        $merchant_list = (new MerchantModel())->where('status' ,'<>',-1)->field('id,merchant_sn,name,company')->select();
        $cost_type_list = (new CostType())
            ->where('type','=',3)
            ->where('pid','=',0)
            ->field('id,cost_name')->select();
        $pay_type = (new SubjectList())->where('type','=',1)->field('id,name')->select();
        $service_charge = (\app\common\model\tang\System::where(['id'=>3])->value('amount'))/100;
        //所属部门
        $department_list = SubjectList::where('type','=',2)->field('id,name')->select();

        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id);
        //获取菜单列表
        $this->assign(compact("info", "id","merchant_list","cost_type_list","department_list","pay_type","service_charge"));
        return $this->fetch();
    }
    public function getCostType()
    {
        $param = $this->request->param();
        $cost_type    = intval($param['cost_type']);  //  缴费类型  1 电费  5 水费
        $number       = intval($param['number']);  //  购买数量
        // 修改后新数据
        $update = empty($param['update'])?[]:$param['update'];
        $cost = (new CostType())->find($cost_type);
        if($cost['is_number']==1){  // 限制办理数量
             if($number>$cost['number']){
                 return self::ajaxResult([],0,1,'购买数量不合法');
             }
        }
        $cost_type_list = (new CostType())->where('pid','=',$cost_type)->field('id,type,cost_name,cost_sn,tax_sn,tax_rate,tax,cost_money,th_money')->select()->toArray();
        if($number<=0){
            return self::ajaxResult([],0,1,'购买数量不合法');
        }
        if (empty($cost_type)){
            return self::ajaxResult([],0,1,'缴费类型不存在');
        }
        $return = [] ;
        if(!empty($cost_type_list)){
            $k = 0 ;
            $data = [] ;
            $unitprice = 0 ;
            foreach ($cost_type_list as $v){
                $k++ ;
                if(!empty($update)){
                    $new_unit_price = [];
                    foreach ($update as $money){
                        if(!empty($money[$v['id']])){
                            $new_unit_price = $money ;
                            break ;
                        }
                    }
                    if(!empty($new_unit_price)){
                        $unit_price = $new_unit_price[$v['id']] ;
                    }else{
                        $unit_price = $v['cost_money'] ;
                    }
                }else{
                    $unit_price = $v['cost_money'] ;
                }
                if($v['tax']==1){
                    $TaxMoneyArr = TaxMoney($unit_price,$number,$v['tax_rate']);
                }else{
                    $TaxMoneyArr = [
                        'tax_money' => 0, // 税率金额
                        'money'     => $unit_price * $number , // 收入金额
                        'z_money'   => $unit_price * $number,  // 总金额
                    ] ;
                }
                $unitprice+=$unit_price ;
                $data[] = [
                    'id'        => $v['id'],
                    'cost_name' => $v['cost_name'],
                    'type'      => $v['type'],
                    'cost_sn'   => $v['cost_sn'], // 收费科目
                    'tax_sn'    => $v['tax_sn'],  // 税率科目
                    'unitprice' => $unit_price,
                    'tax_rate'  => $v['tax_rate'],  // 税率
                    'tax_money' => $TaxMoneyArr['tax_money'], // 税率金额
                    'money'     => round($TaxMoneyArr['money'],2), // 收入金额
                    'z_money'   => round($TaxMoneyArr['money']+$TaxMoneyArr['tax_money'],2),  // 总金额
                ];
            }
            $reality_money = $unitprice * $number ;
            $z_reality_money = round($reality_money,2);
            $return = [
                'data'     => $data,
                'z_money'  => $z_reality_money,
                'is_card'    => $cost['is_card']
            ];
        }
        return self::ajaxResult($return,0,0,'success');
    }
    public function detail()
    {
        $id = $this->request->param("id/d");//父id
//        $info = $this->model->with('Cost')->find($id);
        $info = $this->model->with(['Cost','costRule','merchants','costType'])->find($id);
//        $data = [] ;
//        foreach ($info->Cost as $k => $row){
//            $a = [
//                'id' => $row->id ,
//                'mobile' => $row->mobile ,
//                'username' => $row->username ,
//            ];
//            $data[] = $a;
//        }
//        var_dump($data);die;
        if($info->pay_status==0){
            $info->is_user = '未缴费';
            $info->fees_user = '未缴费';
        }else{
            switch ($info->is_user){
                case 0 :
                    $info->is_user =  '后台缴费';
                    $info->fees_user = $info->merchant->username;
                    break ;
                case 1 :
                    $info->is_user = '自主缴费';
                    $info->fees_user = $info->merchant->username;
                    break ;
            }
        }
        if(empty($info->add_user)){
            $info->add_user = $info->merchant->username;
        }
        $info->cjtime  = date('Y-m-d H:i:s',$info->create_time);
        switch ($info->pay_status){
            case -1 :
                $info->pay_status_name = '已退费';
                break ;
            case 0 :
                $info->pay_status_name = '未支付';
                break ;
            case 1 :
                $info->pay_status_name = '已支付';
                break ;
        }
        if(!empty($info->costRule)){
            foreach ($info->costRule as&$v){
                switch ($v['type']){
                    case 1 :
                        $v['type'] = '押金';
                        break ;
                    case 2 :
                        $v['type'] = '费用';
                        break ;
                    case 3 :
                        $v['type'] = '证件';
                        break ;
                }
            }
        }

        $Subjectinfo = (new SubjectList())->where('id','=',$info->subject_id)->field('name')->find();
        $info->subject_id = $Subjectinfo['name'] ;
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }
    public function staff()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            $id = $data['id'];
            $info = $this->model->find($id);
            if($info){
                Db::startTrans();
                try {
                     // 查询已添加
                    $sum = $this->model->where('pid','=',$info['id'])->count() + count($data['personArray']);
                    if($sum>$info['number']){
                        return parent::JsonReturn('添加的用户数量已达上限', 1);
                    }
                    // 添加施工人员
                    if(!empty($data['personArray'])){
                        $personArray = [];
                        foreach ($data['personArray'] as $k => $row){
                            $is_mobile = $this->model->where('pid','=',$info['id'])->where('mobile','=',$row['mobile'])->find();
                            if($is_mobile){
                                return parent::JsonReturn('手机号【'.$row['mobile'].'】已添加', 1);
                            }
                            if($info['date_type']==0){
                                $personArray[$k]['start_time'] = $info['start_time'];
                                $personArray[$k]['end_time'] = $info['end_time'];
                            }
                            $personArray[$k]['pid'] =  $id ;
                            $personArray[$k]['merchant_id'] = $info['merchant_id'];
                            $personArray[$k]['pay_status'] = 1;
                            $personArray[$k]['unit_price'] = 0;
                            $personArray[$k]['date_type'] = $info['date_type'];
                            $personArray[$k]['department_id'] = $info['department_id'];
                            $personArray[$k]['cost_type_id'] = $info['cost_type_id'];
                            $personArray[$k]['order_sn'] = OrderSn();
                            $personArray[$k]['pay_time'] = date('Y-m-d H:i:s',time());
                            if(!empty($row['mobile'])){
                                $personArray[$k]['mobile'] = $row['mobile'];
                            }else{
                                return parent::JsonReturn('施工人员手机号码不能为空', 1);
                            }
                            if(!empty($row['username'])){
                                $personArray[$k]['username'] = $row['username'];
                            }else{
                                return parent::JsonReturn('施工人员姓名不能为空', 1);
                            }
                            if(!empty($row['card_number'])){
                                $personArray[$k]['card_number'] = $row['card_number'];
                            }
                            if(!empty($row['other_certificate'])){
                                $personArray[$k]['other_certificate'] = $row['other_certificate'];
                            }
                            if(!empty($row['id_card_positive'])){
                                $personArray[$k]['id_card_positive'] = $row['id_card_positive'];
                            }
                            if(!empty($row['id_card_negative'])){
                                $personArray[$k]['id_card_negative'] = $row['id_card_negative'];
                            }
                        }
                        $this->model->insertAll($personArray);
                        Db::commit();
                        return self::JsonReturn("添加成功",0);
                    }else{
                        return parent::JsonReturn('添加人员不能为空', 1);
                    }
                }catch (\Exception $exception){
                    Db::rollback();
                    return self::JsonReturn($exception->getMessage(),0);
                }
            }else{
                return parent::JsonReturn('订单不存在', 1);
            }
        }
        $id = $this->request->param("id/d");
        $info = $this->model->with(['costType'])->find($id);
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }

    // 移除
    public function remove(){
        $id = $this->request->param("id/d");
        $info = $this->model->find($id);
        if($info){
            Db::startTrans();
            try {
                $res = $this->model->where('id', '=',$id)->delete();
                Db::commit();
                return self::JsonReturn("移除成功");
            }catch (\Exception $exception){
                Db::rollback();
                return self::JsonReturn($exception->getMessage(),0);
            }
        }else{
            return parent::JsonReturn('用户不存在', 1);
        }
    }

    public function check(){
        $id = $this->request->param("id/d");
        $info = $this->model->find($id);
        if($info){
            return self::ajaxResult($info,0,0,'success');
        }else{
            return parent::JsonReturn('用户不存在', 1);
        }

    }
    public function invoice()
    {
        $param = $this->request->param();
        $id   = intval($param['id']);
        $model =  new \app\common\model\tang\Cost();
        $cost = $model->find($id);
        if(empty($cost)){
            return self::ajaxResult([],0,1,'不存在的订单');
        }
        $invoice = empty($cost->invoice)?1:0;
        $update = $model->update(['invoice'=>$invoice],['id'=>$id]);
        if($update){
            return self::ajaxResult([],0,0,'修改成功');
        }else{
            return self::ajaxResult([],0,1,'修改失败');
        }

    }

}